import {ActionType, PageContainer, ProColumns, ProTable,} from '@ant-design/pro-components';
import {FormattedMessage, useIntl} from '@umijs/max';
import {Card, message, Modal, Popconfirm, Tabs, Tag} from 'antd';
import React, {useRef, useState} from 'react';
import JsonView from '@uiw/react-json-view';
import RejectForm from './components/RejectForm';
import {approveRequest, myRequests, allRequests, userLike} from '@/services/approval/api';
import {useModel} from '@umijs/max';

const TableList: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser;
  const isSuperAdmin = currentUser?.is_super_admin;

  const [activeTab, setActiveTab] = useState(isSuperAdmin ? 'allApprovals' : 'myRequests');
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<API.ApprovalDetailViewItem>();
  const actionRef = useRef<ActionType | null>(null);

  const isMyRequests = () => {
    return activeTab === 'myRequests';
  }

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const [messageApi, contextHolder] = message.useMessage();

  const fetchApprovalList = async (params: any, sort: any, filter: any) => {
    console.log(activeTab)
    let queryParams;

    if (isSuperAdmin) {
      queryParams = {
        ...params,
      };
    } else {
      //invited：0-发起人 1-受邀人
      queryParams = {
        ...params,
        invited: activeTab === 'myRequests' ? 0 : 1,
      };
    }

    try {
      const result = isSuperAdmin ?
        await allRequests(queryParams, sort, filter) :
        await myRequests(queryParams, sort, filter);
      return {
        ...result,
        success: true,
      };
    } catch (error: any) {
      console.error('ProTable request error:', error);
      messageApi.error(error.data?.message || '列表加载失败，请重试');
      return {
        data: [],
        success: false,
        total: 0,
      };
    }
  };

  const columns: ProColumns<API.ApprovalDetailViewItem>[] = [
    {
      title: (
        <FormattedMessage
          id="pages.approvals.searchTable.id"
          defaultMessage="ID"
        />
      ),
      dataIndex: 'id',
      width: 80,
      hideInSearch: true,
    },
    {
      title: (
        <FormattedMessage
          id="pages.approvals.searchTable.approvableType"
          defaultMessage="业务类型"
        />
      ),
      dataIndex: 'approvableType',
      width: 150,
      order: 10,
      valueType: 'select',
      valueEnum: {
        1: {text: '命名空间变更'},
        2: {text: '开关变更'},
      },
      fieldProps: {
        style: {
          width: '150px',
        },
      },
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.approvals.searchTable.approverUsers"
          defaultMessage="审批人列表"
        />
      ),
      dataIndex: 'approverUsersStr',
      hideInSearch: true,
      hideInForm: true,
      width: 150,
      fieldProps: {
        style: {
          width: '150px',
        },
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.approvals.searchTable.approvalNotes"
          defaultMessage="审批意见"
        />
      ),
      dataIndex: 'approvalNotes',
      hideInForm: true,
      hideInSearch: true,
      width: 150,
      fieldProps: {
        style: {
          width: '150px',
        },
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.approvals.searchTable.requesterUser"
          defaultMessage="发起人"
        />
      ),
      dataIndex: 'requesterUser',
      sorter: true,
      hideInSearch: isMyRequests() || isSuperAdmin,
      hideInForm: true,
      order: 9,
      width: 150,
      valueType: 'select',
      fieldProps: {
        showSearch: true,
        style: {
          width: '150px',
        },
      },
      render: (_, record) => record.requesterUserStr,
      request: async ({keyWords}) => {
        if (!keyWords) {
          return [];
        }
        const res = await userLike({username: keyWords});
        return (res.data || []).map((user: API.CurrentUser) => ({
          label: user.username,
          value: user.id,
        }));
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.approvals.searchTable.createTime"
          defaultMessage="发起时间"
        />
      ),
      sorter: true,
      width: 170,
      hideInSearch: true,
      hideInForm: true,
      order: 1,
      dataIndex: 'createTime',
      key: 'updatedAt',
      valueType: 'dateTimeRange',
      render: (_, record) => {
        if (!record.createTime) return '-';
        return record.createTime.replace('T', ' ').substring(0, 19);
      },
      fieldProps: {
        style: {
          width: '360px',
        },
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.approvals.searchTable.approverUser"
          defaultMessage="审批人"
        />
      ),
      dataIndex: 'approverUser',
      sorter: true,
      order: 9,
      hideInSearch: !isMyRequests() || isSuperAdmin,
      hideInForm: true,
      width: 150,
      valueType: 'select',
      render: (_, record) => record.approverUserStr,
      fieldProps: {
        showSearch: true,
        style: {
          width: '150px',
        },
      },
      request: async ({keyWords}) => {
        if (!keyWords) {
          return [];
        }
        const res = await userLike({username: keyWords});
        return (res.data || []).map((user: API.CurrentUser) => ({
          label: user.username,
          value: user.id,
        }));
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.approvals.searchTable.approvalTime"
          defaultMessage="审批时间"
        />
      ),
      sorter: true,
      hideInSearch: true,
      width: 170,
      dataIndex: 'approvalTime',
      render: (_, record) => {
        if (!record.createTime) return '-';
        return record.createTime.replace('T', ' ').substring(0, 19);
      },
      fieldProps: {
        style: {
          width: '360px',
        },
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.approvals.searchTable.status"
          defaultMessage="状态"
        />
      ),
      dataIndex: 'status',
      hideInForm: true,
      order: 8,
      width: 150,
      valueType: 'select',
      valueEnum: {
        'PENDING': { text: '审批中', status: 'Processing' },
        'APPROVED': { text: '已通过', status: 'Success' },
        'REJECTED': { text: '已拒绝', status: 'Error' },
      },
      render: (_, record) => {
        let color = 'default';
        let text: string = record.status;
        
        if (record.status === 'PENDING') {
          color = 'processing';
          text = '审批中';
        } else if (record.status === 'APPROVED') {
          color = 'success';
          text = '已通过';
        } else if (record.status === 'REJECTED') {
          color = 'error';
          text = '已拒绝';
        }
        return <Tag color={color}>{text}</Tag>;
      },
      fieldProps: {
        style: {
          width: '150px',
        },
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.system.titleOption"
          defaultMessage="操作"
        />
      ),
      dataIndex: 'option',
      valueType: 'option',
      width: 170,
      render: (_, record) => {
        if (activeTab !== 'myRequests' || isSuperAdmin) {
          if (record.status == "PENDING") {
            return [
              <Popconfirm
                title="确认同意审批吗？"
                onConfirm={async () => {
                  await approveRequest({id: record.id, notes: "", status: 1});
                  actionRef.current?.reload();
                }}
              >
                <a>
                  <FormattedMessage id="pages.approvals.searchTable.agree" defaultMessage="同意"/>
                </a>
              </Popconfirm>,
              <RejectForm
                trigger={
                  <a>
                    <FormattedMessage id="pages.approvals.searchTable.reject" defaultMessage="拒绝"/>
                  </a>
                }
                key="reject"
                reload={() => actionRef.current?.reload()}
                values={record}
              />,
            ];
          }
        }
        return null;
      },
    },
  ];

  return (
    <PageContainer>
      {contextHolder}
      <Card>
        <Tabs
          activeKey={activeTab}
          onChange={(key) => {
            setActiveTab(key);
            actionRef.current?.reload();
          }}
        >
          {!isSuperAdmin && <Tabs.TabPane tab="我的申请" key="myRequests"/>}
          {!isSuperAdmin && <Tabs.TabPane tab="待我审批" key="myApprovals"/>}
          {isSuperAdmin && <Tabs.TabPane tab="全部审批" key="allApprovals"/>}
        </Tabs>
        <ProTable<API.ApprovalDetailViewItem, API.PageParams>
          headerTitle={intl.formatMessage({
            id: 'pages.approvals.searchTable.title',
            defaultMessage: '审批列表',
          })}
          actionRef={actionRef}
          rowKey="id"
          search={{
            labelWidth: 'auto',
            span: {
              xs: 24,
              sm: 12,
              md: 8,
              lg: 8,
              xl: 6,
              xxl: 6,
            },
          }}
          request={fetchApprovalList}
          columns={columns}
        />
      </Card>

      {showDetail && (
        <Modal
          title="变更详情"
          open={showDetail}
          onCancel={() => setShowDetail(false)}
          footer={null}
          width={800}
          centered
          destroyOnHidden={true}
        >
          <JsonView
            value={currentRow?.approvable || {}}
            style={{
              backgroundColor: '#f6f8fa',
              padding: '16px',
              borderRadius: '6px'
            }}
            collapsed={false}
          />
        </Modal>
      )}

    </PageContainer>
  );
};

export default TableList;
